<!--
 * @Author: your name
 * @Date: 2021-12-01 09:46:24
 * @LastEditTime: 2021-12-01 10:11:53
 * @LastEditors: Please set LastEditors
 * @Description: 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
 * @FilePath: \front-end-algorithm\算法\字符串替换问题.html
-->
<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>字符串替换</title>
</head>

<body>
    <p>输入：we happy world!</p>
    <p>输出：we%20happy20%world!</p>
    <script>
        /*  let s = '%20';
         let temp = str.split(' ')
         let flag = ""
         for (var i = 0; i < temp.length; i++) {
             if (i == temp.length - 1) {
                 flag += temp[i]
             }
             else {
                 flag += temp[i] + s
             }
         }
         console.log('处理后的字符串是' + flag) */
        let str = 'Hope to see you in YueCheng!';
        let formatStr = (str, rep) => {
            //先判断外层边界被替换的字符是否存在如果不存在就直接返回
            if (typeof rep == 'number' || typeof rep === 'string') {
                if (typeof str === 'string') {
                    if (str.indexOf(" ") > -1) {
                        //如果是string类型就进行处理否则就返回本身；
                        //核心逻辑
                        let orgString = str.split(" ");
                        let resultString = "";
                        for (let i = 0; i < orgString.length; i++) {
                            if (i == orgString.length - 1) {
                                resultString += orgString[i];
                            } else {
                                resultString += (orgString[i] + rep);
                            }
                        }
                        return resultString;
                    } else {
                        //如果不包含空格直接返回
                        return str;
                    }




                } else {
                    return str;
                }
            } else {
                return str;
            }

        }

        console.log(formatStr(str, '%200'));
    </script>
</body>

</html>